﻿using Abp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Core.Tasks.Queue
{
    /// <summary>
    /// 消费队列启动管理
    /// </summary>
    public class ConsumerQueueStartManager : AbpServiceBase, Abp.Dependency.ITransientDependency
    {
        private readonly ISet<IConsumerQueue> consumerQueues;

        public ConsumerQueueStartManager()
        {
            consumerQueues = new HashSet<IConsumerQueue>();
            this.isComplete = false;
        }

        /// <summary>
        /// 添加队列
        /// </summary>
        /// <param name="queue"></param>
        public bool Add(IConsumerQueue queue)
        {
            if (queue == null)
            {
                return false;
            }
            lock (this)
            {
                var result = consumerQueues.Add(queue);
                isComplete = !result;
                return result;
            }
        }

        private bool isComplete = false;

        /// <summary>
        /// 获取是否启动完成
        /// </summary>
        public bool IsComplete
        {
            get
            {
                return isComplete;
            }
        }

        /// <summary>
        /// 启动或检查
        /// </summary>
        public Task StartOrCheck()
        {
            return Task.Run(() =>
            {
                lock (this)
                {
                    if (IsComplete)
                    {
                        return;
                    }
                    var items = consumerQueues.Where(s => !s.IsStarted).ToList();
                    int errorCount = 0;
                    try
                    {
                        foreach (var queue in items)
                        {
                            queue.Start();
                        }
                    }
                    catch (Exception err)
                    {
                        errorCount++;
                        this.Logger.Error("启动消息队列出错:" + err.Message, err);
                    }
                    isComplete = errorCount == 0;
                }
            });
        }
    }
}
